﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Security;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Tools;

namespace SysFrameWork
{
    public class HttpAgreement
    {
        /// <summary>
        /// get请求
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="headerValue">header参数(可为空)</param>
        /// <returns></returns>
        public string HttpGet(string url, string headerValue)
        {
            return this.GetResponseString(CreateGetHttpResponse(url, headerValue));
        }
        private static HttpWebResponse CreateGetHttpResponse(string url, string headerValue)
        {
            HttpWebRequest request = null;
            //如果是发送HTTPS请求
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(url) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }
            if (!string.IsNullOrWhiteSpace(headerValue))
            {
                request.Headers.Add("Authorization", "Basic " + headerValue);
            }
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";//链接类型
            return request.GetResponse() as HttpWebResponse;
        }

        private static bool CheckValidationResult(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }
        private string GetResponseString(HttpWebResponse webresponse)
        {
            using (Stream s = webresponse.GetResponseStream())
            {
                StreamReader reader = new StreamReader(s, Encoding.UTF8);
                return reader.ReadToEnd();
            }
        }


        /// <summary>
        /// Post请求(参数为json格式)
        /// </summary>
        /// <param name="serUrl">方法名称(路径)</param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public string PostJson(string serUrl, string postData, string token)
        {
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serUrl);
            request.ProtocolVersion = HttpVersion.Version10;

           
            request.Method = "POST";
            request.ContentType = "application/json";

            request.Headers.Add("appKey", ConfigReader.Reader["appKey"]);
            //request.Headers["appKey"] = ConfigReader.Reader["appKey"];
            request.Headers["appSecret"] = ConfigReader.Reader["appSecret"];
            request.Headers["openToken"] = token;

            
            //声明一个HttpWebRequest请求
            request.Timeout = 30000;
            //转发机制
            Encoding encoding = Encoding.UTF8;
            Stream streamrequest = request.GetRequestStream();
            StreamWriter streamWriter = new StreamWriter(streamrequest, encoding);
            streamWriter.Write(postData);
            streamWriter.Flush();
            streamWriter.Close();
            streamrequest.Close();

            //设置连接超时时间
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream streamresponse = response.GetResponseStream();
            StreamReader streamReader = new StreamReader(streamresponse, encoding);
            string result = streamReader.ReadToEnd();
            //log.InfoFormat("上传返回信息,{0}", result);
            streamresponse.Close();
            streamReader.Close();

            return result;
        }

        public string Get(string url, string hvalue,string tokenKey = null)
        {
            TxtLogHelper tx = new TxtLogHelper();
            string result = string.Empty;

            StringBuilder sb = new StringBuilder();
            sb.Append(url);
            sb.Append("?grantType="+ ConfigReader.Reader["grantType"]);
            sb.Append("&refreshToken=" + ConfigReader.Reader["refreshToken"]);
           
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(sb.ToString());
            tx.AddLogMsg(string.Format("url:{0},value:{1}", url, hvalue));
            req.Method = "GET";
            //req.ContentType = "application/x-www-form-urlencoded";
            req.ContentType = "application/json";
            if (!string.IsNullOrWhiteSpace(hvalue))
            {
                req.Headers["Authorization"] = "Basic " + hvalue;
            }

            if (!string.IsNullOrWhiteSpace(tokenKey))
            {
                req.Headers["appKey"] = ConfigReader.Reader["appKey"];
                req.Headers["appSecret"] = ConfigReader.Reader["appSecret"];
            }

            // req.Headers["Authorization"] = "Basic trademark:d0c9881aaabb0fd2525a27e5570bcaac";
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }




        public string HttpPost(string url, string postDataStr, string token)
        {
            //WebRequest myRequest = WebRequest.Create("https://www.baidu.com");

            //WebResponse myResponse = myRequest.GetResponse();

            //myResponse.Close();

            string strReturn;
            //在转换字节时指定编码格式
            byte[] byteData = Encoding.UTF8.GetBytes(postDataStr);

            //配置Http协议头
            HttpWebRequest resquest = (HttpWebRequest)WebRequest.Create(url);
            resquest.Method = "POST";
            //resquest.ContentType = "application/x-www-form-urlencoded";
            resquest.ContentType = "application/json";
            resquest.ContentLength = byteData.Length;

            resquest.Headers.Add("appKey", ConfigReader.Reader["appKey"]);
            //request.Headers["appKey"] = ConfigReader.Reader["appKey"];
            resquest.Headers["appSecret"] = ConfigReader.Reader["appSecret"];
            resquest.Headers["openToken"] = token;


            //声明一个HttpWebRequest请求
            resquest.Timeout = 30000;

            //发送数据
            using (Stream resquestStream = resquest.GetRequestStream())
            {
                resquestStream.Write(byteData, 0, byteData.Length);
            }

            WebResponse response;
            try
            {
                response = resquest.GetResponse();
            }
            catch (WebException ex)
            {
                response = ex.Response;
            }
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
            strReturn = reader.ReadToEnd();
            reader.Close();
            reader.Dispose();

            ////接受并解析信息
            //using (WebResponse response = resquest.GetResponse())
            //{
            //    //解决乱码：utf-8 + streamreader.readToEnd
            //    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
            //    strReturn = reader.ReadToEnd();
            //    reader.Close();
            //    reader.Dispose();
            //}


            return strReturn;
        }



        /// <summary>
        /// 判断地址是否能正常访问
        /// </summary>
        /// <param name="url">目标地址</param>
        /// <returns></returns>
        public bool ToWebPage(string url)
        {
            try
            {

                // Creates an HttpWebRequest for the specified URL.
                HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                // 有些网站会阻止程序访问，需要加入下面这句
                myHttpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko";
                myHttpWebRequest.Method = "GET";
                // Sends the HttpWebRequest and waits for a response.
                HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
                if (myHttpWebResponse.StatusCode == HttpStatusCode.OK)
                {
                    return true;
                }
                else
                {
                    return false;
                }


            }
            catch (WebException e)
            {
                return false;
            }
            catch (Exception e)
            {
                return false;
            }
        }
    }
}
